#pragma once
#include <iostream>
#include <string>
#include <pthread.h>

namespace ThreadMoudle
{
    class ThreadData
    {
        public:
        ThreadData(const std::string&name,pthread_mutex_t *lock)
        :_name(name),_lock(lock){}
        std::string _name;
        pthread_mutex_t *_lock;
    };
    typedef void (*func_t)(ThreadData*td);
    class Thread
    {
        void Excute()
        {
            std::cout << _name << "is running " << std::endl;
            _isrunning = true;
            _func(_td);
            _isrunning = false;
        }
        static void *ThreadRoutine(void *args)
        {
            Thread *self = static_cast<Thread *>(args);
            self->Excute();
            return nullptr;
        }

    public:
        Thread(const std::string name, func_t func,ThreadData*td)
            : _name(name), _func(func), _td(td){}

        bool Start()
        {
            int n = ::pthread_create(&_tid, nullptr, ThreadRoutine, this);
            if (n != 0)
                return false;
            return true;
        }
        std::string Status()
        {
            if (_isrunning)
                return "running";
            else
                return "sleep";
        }
        void Join()
        {
            ::pthread_join(_tid, nullptr);
            std::cout << _name << " join" << std::endl;
        }
        void Stop()
        {
            if (_isrunning)
            {
                ::pthread_cancel(_tid);
                _isrunning = false;
                std::cout << _name << " Stop" << std::endl;
            }
        }
        ~Thread() {}

    private:
        std::string _name;
        pthread_t _tid;
        bool _isrunning;
        func_t _func; // 线程要执行的回调函数

        ThreadData*_td;
    };
}
